import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:signage/app/data/models/member_group_model.dart';
import 'package:signage/app/data/models/member_info_item_model.dart'; // 添加这行导入

import 'package:get_storage/get_storage.dart';
import 'package:flutter/material.dart';
import 'package:signage/app/modules/cast/chooseList/views/add_member_dialog.dart';
import 'package:file_picker/file_picker.dart';
import 'package:signage/app/utils/sp_util.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:signage/widgets/edit_dialog.dart';
import 'package:spreadsheet_decoder/spreadsheet_decoder.dart';

class ChooseListController extends GetxController {
  static const String GROUPS_KEY = 'member_groups';

  final count = 0.obs;
  var groupList = [].obs;
  var currentGroup = Rxn<MemberGroup>();
  var currentGroupIndex = 0.obs;
  var templateModelA;
  var templateModelB;
  var isSelecting = false.obs;
  var sampleValue = 1; // 添加 sampleValue 变量

  @override
  void onInit() async {
    super.onInit();
    loadGroups(); // 初始化时加载保存的分组
    initMemberSelection();
  }

  // 加载保存的分组
  void loadGroups() {
    try {
      final savedGroups = SpUtil.getList(GROUPS_KEY);
      if (savedGroups != null) {
        print('存储的分组不为空');
        final List<dynamic> groupsJson = savedGroups;
        groupList.value =
            groupsJson.map((json) => MemberGroup.fromJson(json)).toList();
      }
    } catch (e) {
      print('加载分组失败: $e');
    }
  }

  // 保存分组
  void saveGroups() {
    try {
      final groupsJson = groupList.map((group) => group.toJson()).toList();
      SpUtil.setList(GROUPS_KEY, groupsJson);
    } catch (e) {
      print('保存分组失败: $e');
    }
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void increment() => count.value++;
  MemberGroup? getIndexGroup(int index) {
    if (groupList.length > index) {
      MemberGroup group = groupList[index];
      print("当前的${group.groupName}");
      return group;
    } else {
      return null;
    }
  }

  touchGroupSeg(int index) {
    print("点击了${index}");
    if (groupList.length > index) {
      MemberGroup group = groupList[index];
      currentGroup.value = group;
      currentGroupIndex.value = index;
      print("当前的${group.groupName}");
    }
  }

  touchGroupSegDelete(int index) async {
    if (groupList.length > index) {
      final result = await Get.dialog(
        TipsDialog(
          title: AppLocalizations.of(Get.context!)!.translate('tips'),
          text: AppLocalizations.of(Get.context!)!.translate('confirm_delete_group'),
          showCancel: true,
          onConfirm: () {
            Get.back();
            groupList.removeAt(index);
            if (groupList.isNotEmpty) {
              currentGroup.value = groupList.first;
            }
            saveGroups();
          },
        ),
      );
    }
  }

  void confirmSelection() {
    saveGroups();
    Get.back(result: {
      'memberList': currentGroup.value?.memberList
          ?.where((member) => member.choose == true)
          .toList(),
      'groupName': currentGroup.value?.groupName,
      'groupId': currentGroup.value?.id
    });
  }

  void addNewGroup() {
    MemberGroup newGroup = MemberGroup(
      id: groupList.length + 1,
      groupName: AppLocalizations.of(Get.context!)!.translate(
        'cast_new_group',
        params: {'number': (groupList.length + 1).toString()}
      ),
      memberList: [],
    );
    groupList.insert(0, newGroup);
    touchGroupSeg(0);
    saveGroups(); // 添加新分组后保存
  }

  void initMemberSelection() {
    if (Get.arguments != null) {
      final args = Get.arguments as Map;
      final mode = args['mode'];
      final memberList = args['memberList'];
      final groupName = args['groupName'];
      final groupId = args['groupId'];
      print("初始化成员选择 ${args}");
      isSelecting.value = mode != 'view';

      if (mode == 'view' || mode == 'edit') {
        // 先加载所有分组
        loadGroups();

        // 根据groupId查找对应分组
        if (groupId != null) {
          final targetGroup =
              groupList.firstWhereOrNull((group) => group.id == groupId);

          if (targetGroup != null) {
            // 编辑模式下设置选中状态
            if (mode == 'edit' && memberList != null) {
              currentGroup.value = targetGroup;

              print('编辑模式 - 设置选中状态');
              print('传入的成员列表: ${memberList.length}人');

              // 只选中共有的成员
              for (final member in currentGroup.value?.memberList ?? []) {
                for (final m in memberList) {
                  if (member.id == m.id) {
                    member.choose = true;
                  }
                }
              }
              currentGroup.refresh();
            } else {
              currentGroup.value = targetGroup;

              currentGroup.value?.memberList = memberList;
              print('查看模式 - 设置成员列表 ${currentGroup.value?.memberList?.length}人');
            }
          }
        }
      } else {
        // 选择模式：加载已保存的分组

        if (groupList.isNotEmpty) {
          currentGroup.value = groupList.first;
          print(
              '选择模式 - 加载已保存的分组 ${currentGroup.value?.memberList?.length}人 ${groupList.length}存储组');
        } else {
          // 如果没有分组，创建一个默认分组
          currentGroup.value = MemberGroup(
            id: 1,
            groupName: AppLocalizations.of(Get.context!)!.translate('default_group'),
            memberList: [],
          );
          groupList.add(currentGroup.value!);
          saveGroups();
        }
      }

      // 保存模板信息（如果有）
      if (args['templateA'] != null) {
        templateModelA = args['templateA'];
      }
      if (args['templateB'] != null) {
        templateModelB = args['templateB'];
      }

      // 获取 sampleValue
      if (args['sampleValue'] != null) {
        sampleValue = args['sampleValue'];
      }
    } else {
      // 无参数时默认为选择模式
      isSelecting.value = true;
      loadGroups();
      if (groupList.isNotEmpty) {
        currentGroup.value = groupList.first;
      } else {
        // 如果没有分组，创建一个默认分组
        currentGroup.value = MemberGroup(
          id: 1,
          groupName: AppLocalizations.of(Get.context!)!.translate('default_group'),
          memberList: [],
        );
        groupList.add(currentGroup.value!);
        saveGroups();
      }
    }
  }

  void addMember(MemberItem newMember) {
    if (currentGroup.value != null) {
      // 初始化memberList如果为空
      if (currentGroup.value?.memberList == null) {
        currentGroup.value?.memberList = [];
      }

      // 添加新成员，并设置为选中状态
      newMember.choose = true;
      currentGroup.value?.memberList?.add(newMember);
      currentGroup.refresh();

      // 更新对应的分组
      if (currentGroup.value?.id != -1) {
        // 不是临时查看/编辑模式
        final index =
            groupList.indexWhere((group) => group.id == currentGroup.value?.id);
        if (index != -1) {
          groupList[index] = currentGroup.value!;
          saveGroups(); // 持久化存储
        }
      }
    }
  }

  void removeMember(int memberIndex) {
    if (currentGroup.value != null &&
        currentGroup.value!.memberList != null &&
        memberIndex < currentGroup.value!.memberList!.length) {
      // 删除成员
      currentGroup.value?.memberList?.removeAt(memberIndex);
      currentGroup.refresh();

      // 更新对应的分组
      if (currentGroup.value?.id != -1) {
        // 不是临时查看/编辑模式
        final index =
            groupList.indexWhere((group) => group.id == currentGroup.value?.id);
        if (index != -1) {
          groupList[index] = currentGroup.value!;
          saveGroups(); // 持久化存储
        }
      }
    }
  }

  void showAddMemberDialog(BuildContext context) {
    print("显示添加成员对话框 sampleValue ${sampleValue}");
    showModalBottomSheet(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10.w),
          topRight: Radius.circular(10.w),
        ),
      ),
      backgroundColor: Colors.white,
      context: context,
      scrollControlDisabledMaxHeightRatio: 0.8,
      builder: (BuildContext context) {
        return ClipRRect(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10.w),
            topRight: Radius.circular(10.w),
          ),
          child: Scaffold(
            backgroundColor: Colors.white,
            body: AddMemberDialog(
              templateModelA: templateModelA,
              templateModelB: templateModelB,
              sampleValue: sampleValue,
              onMemberAdded: addMember,
            ),
          ),
        );
      },
    );
  }

  void showEditMemberDialog(int index, MemberItem member) {
    showModalBottomSheet(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10.w),
          topRight: Radius.circular(10.w),
        ),
      ),
      backgroundColor: Colors.white,
      context: Get.context!,
      scrollControlDisabledMaxHeightRatio: 0.8,
      builder: (BuildContext context) {
        return ClipRRect(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10.w),
            topRight: Radius.circular(10.w),
          ),
          child: Scaffold(
            backgroundColor: Colors.white,
            body: AddMemberDialog(
              templateModelA: templateModelA,
              templateModelB: templateModelB,
              sampleValue: sampleValue,
              onMemberAdded: (member2) {
                currentGroup.value?.memberList?[index].memberInfoList =
                    member2.memberInfoList;
                currentGroup.refresh();

                // 更新对应的分组
                if (currentGroup.value?.id != -1) {
                  // 不是临时查看/编辑模式
                  final index = groupList.indexWhere(
                      (group) => group.id == currentGroup.value?.id);
                  if (index != -1) {
                    groupList[index] = currentGroup.value!;
                    saveGroups(); // 持久化存储
                  }
                }
              },
              member: member,
            ),
          ),
        );
      },
    );
  }

  void deleteMember(MemberItem member) {
    if (currentGroup.value?.memberList != null) {
      currentGroup.update((group) {
        group?.memberList?.remove(member);
      });
      saveGroups(); //
    }
  }

  Future<void> showDeleteConfirmDialog(MemberItem info) async {
    final result = await Get.dialog(
      TipsDialog(
        title: AppLocalizations.of(Get.context!)!.translate('tips'),
        text: AppLocalizations.of(Get.context!)!.translate('confirm_delete_member'),
        showCancel: true,
        onConfirm: () {
          Get.back();
          deleteMember(info);
        },
      ),
    );
  }

  void showImportDialog(BuildContext context) async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['xlsx'],
        withData: true,
      );

      if (result != null) {
        final file = result.files.first;

        // 验证文件扩展名
        if (!file.name.toLowerCase().endsWith('.xlsx')) {
          Get.snackbar(
            AppLocalizations.of(context)!.translate('format_error'),
            AppLocalizations.of(context)!.translate('please_select_excel'),
            duration: Duration(seconds: 3),
            snackPosition: SnackPosition.TOP,
          );
          return;
        }

        if (file.bytes == null) {
          throw AppLocalizations.of(context)!.translate('cannot_read_file');
        }

        var decoder = SpreadsheetDecoder.decodeBytes(file.bytes!, update: true);

        // 遍历每个工作表作为一个分组
        decoder.tables.forEach((sheetName, sheet) {
          if (sheet.rows.length < 3) {
            // 至少需要分组名、表头和数据行
            throw '工作表 $sheetName 数据格式不正确';
          }

          // 获取分组名（第一行第一列）
          String groupName = sheet.rows[0][0]?.toString() ?? 
              AppLocalizations.of(context)!.translate('new_group', 
              params: {'number': (groupList.length + 1).toString()});

          // 创建新分组
          MemberGroup newGroup = MemberGroup(
            id: groupList.length + 1,
            groupName: groupName,
            memberList: [],
          );

          // 获取表头（第二行）
          var headers = sheet.rows[1];

          // 从第三行开始处理数据
          for (var i = 2; i < sheet.rows.length; i++) {
            var row = sheet.rows[i];
            List<MemberInfoItem> memberInfoList = [];

            for (var j = 0; j < headers.length; j++) {
              String headerName = headers[j]?.toString() ?? '';
              String value = row[j]?.toString() ?? '';

              if (headerName.isNotEmpty && value.isNotEmpty) {
                memberInfoList.add(MemberInfoItem(
                    keyName: headerName, type: 'A', value: value));
              }
            }

            var newMember = MemberItem(
                id: i - 1, // 减1因为我们跳过了表头
                memberInfoList: memberInfoList,
                choose: false);

            newGroup.memberList?.add(newMember);
          }

          // 添加新分组到列表
          groupList.insert(0, newGroup);
        });

        // 更新当前分组和保存
        if (groupList.isNotEmpty) {
          currentGroup.value = groupList.first;
          saveGroups();
        }

        Get.snackbar(
          AppLocalizations.of(context)!.translate('success'),
          AppLocalizations.of(context)!.translate('import_success', 
          params: {'count': decoder.tables.length.toString()}));
      }
    } catch (e) {
      print('导入失败: $e');
      Get.snackbar(
        AppLocalizations.of(context)!.translate('error'),
        AppLocalizations.of(context)!.translate('import_failed_message', 
        params: {'error': e.toString()}),
        duration: Duration(seconds: 5),
        snackPosition: SnackPosition.TOP,
      );
    }
  }

  // 辅助方法：查找列索引
  int _findColumnIndex(List<dynamic>? headers, String columnName) {
    if (headers == null) return -1;
    return headers.indexWhere((header) =>
        header?.value.toString().trim().toLowerCase() ==
        columnName.toLowerCase());
  }

  // 辅助方法：获取单元格值
  String _getCellValue(dynamic cell) {
    if (cell == null) return '';
    return cell.value?.toString() ?? '';
  }

  clearMemberList() {
    Get.dialog(
      TipsDialog(
        title: AppLocalizations.of(Get.context!)!.translate('cast_confirm'),
        text: AppLocalizations.of(Get.context!)!.translate('cast_confirm_clear'),
        showCancel: true,
        onConfirm: () {
          Get.back();
          currentGroup.value?.memberList?.clear();
          currentGroup.refresh();
          saveGroups();
        },
      ),
    );
  }

  void copyMember(MemberItem info) {
    addMember(info);
  }
}
